package com.example.mingyue.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mingyue.Exception.LoginFailedException;
import com.example.mingyue.constant.MessageConstant;
import com.example.mingyue.constant.WxConstant;
import com.example.mingyue.mapper.UserMapper;
import com.example.mingyue.model.dto.UserLoginDto;
import com.example.mingyue.model.entity.User;
import com.example.mingyue.properties.WechatProperties;
import com.example.mingyue.service.UserService;
import com.example.mingyue.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author 我自飞扬临天下
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-01-09 12:05:05
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatProperties wechatProperties;


    @Override
    public User userLogin(UserLoginDto userDto) {
        //获取微信用户唯一标识openid
        String openid = getOpenId(userDto);

        if(openid == null){
            //登录失败
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);

        }
        //判断是否未新用户
        User user = userMapper.newUserByOpenId(openid);
        if(user == null){
            //就是新用户,需要添加用户
            User user1 = new User();
            user1.setOpenid(openid);
            user1.setCreateTime(new Date());
            userMapper.addUser(user1);
        }
        return user;
    }
    //获取openid
    public String getOpenId(UserLoginDto userDto){
        //map是请求参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",wechatProperties.getAppId());
        map.put("secret",wechatProperties.getAppSecret());
        map.put("js_code",userDto.getCode());
        map.put("grant_type","authorization_code");

        String json = HttpClientUtils.getRequest(WxConstant.WX_LOGIN,map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }


}




